<template>
    <Dialog :app-dialog="appDialog" @close="closeDialog">
        <!-- 搜索 -->
        <Search
            ref="SearchRef"
            v-model="isReadyInit"
            v-model:default_sea="default_sea"
            v-model:params="paramsForm"
            class="mb15"
            @submit="initList">
        </Search>
        <el-table
            ref="TableRef"
            class="mb15"
            row-key="id"
            :class="{ hide_All: single }"
            height="360"
            header-row-class-name="table_header_title"
            :data="customerList"
            stripe
            style="width: 100%"
            @select-all="selectAll"
            @select="selectGroup">
            <el-table-column type="selection" :reserve-selection="true" width="55" />
            <el-table-column prop="words_name" label="用户姓名" align="left">
                <template #default="{ row }">
                    <div v-if="row.type == 1" class="avatar_box">
                        <el-image class="avatar" :src="row.cust_baseinfo?.avatar">
                            <template #error>
                                <el-image class="avatar" src="/static/file/pic.png"></el-image>
                            </template>
                        </el-image>
                        <div>
                            <div>{{ row?.mobile }}</div>
                            <span>{{ row.cust_baseinfo?.name }} </span>
                            <img
                                v-if="row.cust_baseinfo?.sex === 1"
                                calss="avator_icon"
                                src="@/assets/chatDetails/male.png" />
                            <img
                                v-if="row.cust_baseinfo?.sex === 2"
                                calss="avator_icon"
                                src="@/assets/chatDetails/female.png" />
                        </div>
                    </div>
                    <div v-if="row.type == 2" class="avatar_box">
                        <el-image class="avatar" src="/static/file/pic.png"></el-image>
                        <div>
                            <div>{{ row.short_name ? row.short_name : row.crop_name ? row.crop_name : '--' }}</div>
                            <span style="color: #888; font-size: 12px"
                                >共{{ row?.contact?.length || '0' }}名联系人
                            </span>
                            <span v-if="row?.contact?.length" style="color: #1890ff; font-size: 12px; cursor: pointer">
                                <el-popover placement="right" :width="320" trigger="click">
                                    <template #reference>
                                        <span>查看</span>
                                    </template>
                                    <div class="popoverContent">
                                        <div v-for="item in row.contact" :key="item.name" class="popoverItem">
                                            <div class="img">
                                                <img v-if="item.avatar" :src="item.avatar" alt="" />
                                            </div>
                                            <div class="msg">
                                                <h3>{{ item.name }}</h3>
                                                <h5>上次跟进时间：{{ item.last_follow_time || '--' }}</h5>
                                            </div>
                                            <div class="wx">
                                                <img v-if="item.add_status == 1" :src="getImageUrl('wx_add')" alt="" />
                                                <img
                                                    v-if="item.add_status == 0"
                                                    :src="getImageUrl('wx_unadd')"
                                                    alt="" />
                                            </div>
                                        </div>
                                    </div>
                                </el-popover>
                            </span>
                        </div>
                    </div>
                </template>
            </el-table-column>
            <el-table-column label="归属员工" align="center">
                <template #default="scope">
                    <el-popover
                        v-if="scope.row.assign_employees && scope.row.assign_employees?.split('、').length > 2"
                        placement="top"
                        :width="400"
                        trigger="hover"
                        popper-class="popper">
                        <template #reference>
                            <div class="tag_box">
                                {{ scope.row.can_contact }}
                            </div>
                        </template>
                        <div class="pop_dialog">
                            <span v-for="item in scope.row.assign_employees" :key="item">{{ item }}</span>
                        </div>
                    </el-popover>
                    <div v-else>
                        <div class="tag_box">
                            <span v-for="item in scope.row.assign_employees" :key="item">{{ item }}</span>
                        </div>
                    </div>
                    <span v-if="!scope.row.assign_employees">--</span>
                </template>
            </el-table-column>
            <el-table-column prop="current_stage_name" label="客户阶段" align="center"></el-table-column>
            <el-table-column prop="created_at" label="添加时间" align="center"></el-table-column>
            <template #empty>
                <img class="emty_img" src="@/assets/noData.png" alt="" />
                <div class="emty_title">{{ '暂无数据' }}</div>
            </template>
        </el-table>

        <ZWPagination ref="paginationRef" @submit="fnGetContactList" />
    </Dialog>
</template>
<script setup lang="ts">
import { reactive, ref, onMounted, watchEffect, nextTick } from 'vue';
import { ElMessage } from 'element-plus';

import { getCenterCustomerList } from '@/api/customerCenter';

import customerPopover from '@/view/customer/manage/sea/components/customerPopover.vue';

import Search from './Search.vue';
import Dialog from '@/components/Dialog.vue';
import ZWPagination from '@/components/ZWPagination.vue';

import { useStore } from '@/store';
const store = useStore();
const TableRef = ref<HTMLElement | null>(null);
const customerList = reactive([]);
const selected = ref([]);
const single = ref(false); //单选
const echoDataId = ref([]); //回显数据
const emits = defineEmits(['submit']);

const isReadyInit = ref<boolean>(false);
const default_sea = ref<number>();
const paramsForm = ref<any>({});

const getImageUrl = (name: string): any => {
    return new URL(`../../assets/customer/${name}.png`, import.meta.url).href;
};

// table 表单的全选
const selectAll = (row: any) => {
    selected.value = row;
};
// 选择群聊
const selectGroup = (val: any, row: any) => {
    if (single.value) {
        TableRef.value.clearSelection();
        TableRef.value.toggleRowSelection(row, true);
        selected.value = [row];
    } else {
        selected.value = val;
    }
};

// 取消
const cancelHandel = () => {
    appDialog.visible = false;
    selected.value = [];
};
//确定
const submitHandel = () => {
    emits('submit', selected.value);

    cancelHandel();
};
// 客户列表
const fnGetContactList = async (data?: any) => {
    const params = {
        page: data?.page || 1,
        page_size: data?.page_size || 15,
        select_tag_type: -1,
        is_wx_work: -1,
        touch_mode: -1,
        cust_status: -1,
        // 测试是李曼提的问题。
        // 问题的现象是员工任务-任务管理-新建任务：步骤二选择客户列表接口不返回数据.导致在页面中无法选择客户

        // 原先是0，现在改成空数组，为了目的是契合客户列表的字段，但是这个字段在搜索表单里没有。
        // 不确定为什么不需要的情况下，加上这个字段。但是先不删除。
        group_chat: [],
        // 原先是0，现在改成空字符，同上.,
        // 这个字段是客户保护，0和空字符串都是全部的意思
        protect: '',
        ...data,
        ...paramsForm.value
    };
    const res: any = await getCenterCustomerList(params, true);
    const { data: data2, total } = res;
    customerList.splice(0);
    customerList.push(...data2);
    if (echoDataId.value.length > 0) {
        const arr: any[] = data2.filter((item: any) => echoDataId.value.includes(item.id));
        nextTick(() => {
            arr.forEach((item: any) => {
                TableRef.value.toggleRowSelection(item, true);
            });
        });
    }
    store.dispatch('pageTotal', total);
    // 客户列表初始化
    const initList = (data?: any) => {
        const params = {
            page: 1,
            page_size: 15,
            seas_id: [default_sea.value],
            ...data
        };
        // 此处 seas_id 参数 在接口里时有异常
        fnGetContactList(params);
    };
    store.dispatch('pageTotal', total);
};

const filterParams = (str: string): string => {
    str = str.replace(/\+/g, '%2B');
    str = str.replace(/\&/g, '%26');
    return str;
};

// 客户列表初始化
const initList = (data?: any, isClear?: any) => {
    if (isClear) {
        TableRef.value.clearSelection();
    }
    const params = {
        page: 1,
        page_size: 15,
        seas_id: [default_sea.value],
        ...data
    };
    // 此处 seas_id 参数 在接口里时有异常
    fnGetContactList(params);
};
const appDialog = reactive({
    visible: false,
    title: '选择客户',
    width: '71rem',
    cancel: cancelHandel,
    submit: submitHandel,
    cancelText: '取消',
    submitText: '保存'
});

const closeDialog = (): void => {
    store.dispatch('pageTotal', 0);
};

watchEffect(() => {
    if (isReadyInit.value) {
        initList();
    }
});
defineExpose({
    appDialog,
    single,
    echoDataId
});
</script>

<style lang="scss" scoped>
.mb15 {
    margin-bottom: 15px;
}

.avatar_box {
    display: flex;

    .avatar {
        width: 40px;
        height: 40px;

        // vertical-align: middle;
        margin-right: 5px;
    }

    .avator_icon {
        vertical-align: middle;
        margin-left: 5px;
    }
}

:deep .table_header_title {
    height: 60px;

    th.el-table__cell {
        background: #f9f9f9;
        padding: 10px 0;
    }
}

.hide_All {
    :deep .el-table__header-wrapper {
        thead .table_header_title .el-checkbox {
            display: none;
        }
    }
}

.popoverContent {
    background-color: #fff;

    .popoverItem {
        margin: 0 10px;
        height: 60px;
        display: flex;
        align-items: center;
        border-bottom: 1px solid #eee;

        &:last-of-type {
            border-bottom: none;
        }

        .img {
            width: 40px;
            height: 40px;
            border-radius: 8px;

            // background-color: #eee;

            img {
                width: 100%;
                height: 100%;
            }
        }

        .msg {
            margin: 0 10px;

            h3 {
                margin-bottom: 8px;
                font-size: 13px;
            }

            h5 {
                color: #aaa;
                font-size: 12px;
                width: 212px;
            }
        }

        .wx {
            width: 22px;
            height: 22px;

            img {
                width: 100%;
                height: 100%;
            }
        }
    }
}
</style>
